package rabbitmq

import (
	"github.com/streadway/amqp"
	"go-gin-api/core/config"
	"log"
)

var channel *amqp.Channel

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

func init() {
	url := "amqp://guest:guest@" + config.GetString("rabbitmq.host") + ":" + config.GetString("rabbitmq.port") + "/"
	conn, err := amqp.Dial(url)
	failOnError(err, "Failed to connect to RabbitMQ")

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	channel = ch
	defer func(ch *amqp.Channel) {
		closeErr := ch.Close()
		if closeErr != nil {
			log.Fatalf("Failed to close channel: %s", closeErr)
		}
	}(ch)
}

func send(queue string, body string) {

	q, err := channel.QueueDeclare(
		queue, // name
		false, // durable
		false, // delete when unused
		false, // exclusive
		false, // no-wait
		nil,   // arguments
	)
	failOnError(err, "Failed to declare a queue")

	err = channel.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(body),
		})
	failOnError(err, "Failed to publish a message")
}
